package com.hilin.test.fs;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.HashSet;
import java.util.Set;

@Slf4j
@Component
@ServerEndpoint("/ws/event")
public class WebsocketConnect {

    private static final Object LOCK = new Object();

    private static final Set<Session> CONNECTS = new HashSet<>();

    @OnOpen
    public void onOpen(Session session) {
        synchronized (LOCK) {
            CONNECTS.add(session);
        }
    }

    @OnMessage
    public void onMsg(String text) {
        log.info(text);
    }

    @OnClose
    public void onClose(Session session) {
        synchronized (LOCK) {
            CONNECTS.remove(session);
        }
    }

    public static void send(String msg) {
        synchronized (LOCK) {
            for (Session connect : CONNECTS) {
                try {
                    connect.getAsyncRemote().sendText(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
